﻿using System;

namespace UniRx.Operators
{
	// Token: 0x020002AD RID: 685
	internal class FromEventObservable<TDelegate> : OperatorObservableBase<Unit>
	{
		// Token: 0x06000EFA RID: 3834 RVA: 0x00045F06 File Offset: 0x00044306
		public FromEventObservable(Func<Action, TDelegate> conversion, Action<TDelegate> addHandler, Action<TDelegate> removeHandler) : base(false)
		{
			this.conversion = conversion;
			this.addHandler = addHandler;
			this.removeHandler = removeHandler;
		}

		// Token: 0x06000EFB RID: 3835 RVA: 0x00045F24 File Offset: 0x00044324
		protected override IDisposable SubscribeCore(IObserver<Unit> observer, IDisposable cancel)
		{
			FromEventObservable<TDelegate>.FromEvent fromEvent = new FromEventObservable<TDelegate>.FromEvent(this, observer);
			return (!fromEvent.Register()) ? Disposable.Empty : fromEvent;
		}

		// Token: 0x040008AB RID: 2219
		private readonly Func<Action, TDelegate> conversion;

		// Token: 0x040008AC RID: 2220
		private readonly Action<TDelegate> addHandler;

		// Token: 0x040008AD RID: 2221
		private readonly Action<TDelegate> removeHandler;

		// Token: 0x020002AE RID: 686
		private class FromEvent : IDisposable
		{
			// Token: 0x06000EFC RID: 3836 RVA: 0x00045F4F File Offset: 0x0004434F
			public FromEvent(FromEventObservable<TDelegate> parent, IObserver<Unit> observer)
			{
				this.parent = parent;
				this.observer = observer;
			}

			// Token: 0x06000EFD RID: 3837 RVA: 0x00045F68 File Offset: 0x00044368
			public bool Register()
			{
				this.handler = this.parent.conversion(new Action(this.OnNext));
				try
				{
					this.parent.addHandler(this.handler);
				}
				catch (Exception error)
				{
					this.observer.OnError(error);
					return false;
				}
				return true;
			}

			// Token: 0x06000EFE RID: 3838 RVA: 0x00045FDC File Offset: 0x000443DC
			private void OnNext()
			{
				this.observer.OnNext(Unit.Default);
			}

			// Token: 0x06000EFF RID: 3839 RVA: 0x00045FF0 File Offset: 0x000443F0
			public void Dispose()
			{
				if (this.handler != null)
				{
					this.parent.removeHandler(this.handler);
					this.handler = default(TDelegate);
				}
			}

			// Token: 0x040008AE RID: 2222
			private readonly FromEventObservable<TDelegate> parent;

			// Token: 0x040008AF RID: 2223
			private readonly IObserver<Unit> observer;

			// Token: 0x040008B0 RID: 2224
			private TDelegate handler;
		}
	}
}
